package com.qfedu.fmmall.controller;


import com.github.wxpay.sdk.WXPayUtil;
import com.qfedu.fmmall.service.OrdersService;
import com.qfedu.fmmall.websocket.WebSocketServer;
import org.springframework.http.HttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : yanBin
 * @date :2021/12/21 13:38
 */
@RestController
@RequestMapping("/pay")
public class PayController {

    @Resource
    private OrdersService ordersService;

    @RequestMapping("/callback")
    public String payCallback(HttpServletRequest request) {
        try {
            //用字节写入流
            ServletInputStream is = request.getInputStream();
            byte[] bs = new byte[1024];
            int len = -1;
            StringBuffer sb = new StringBuffer();
            while ((len = is.read(bs)) != -1) {
                sb.append(new String(bs, 0, len));
            }
            is.close();
            //得到微信响应字符串
            String s = sb.toString();
            //把得到的微信响应字符串转换成map

            Map<String, String> map = WXPayUtil.xmlToMap(s);
            if (!CollectionUtils.isEmpty(map) && "success".equals(map.get("result_code"))) {
                //修改订单状态为”待发货“
                int i = ordersService.updateOrdersByStatus(map.get("out_trade_on"), "2");
                if (i <= 0) {
                    return null;
                }
                //用websocket发送前端付款结果
                WebSocketServer.sendMsg(map.get("out_trade_on"),"1");
                //响应给平台
                Map<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("app_id", map.get("appid"));
                resp.put("result", "success");
                return WXPayUtil.mapToXml(resp);
            }

        } catch (Exception e) {
            return null;
        }

        return null;
    }

}
